<?php

namespace Icsoc\PhoneManageBundle\Controller;

use Icsoc\CoreBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class PhoneController
 * @package Icsoc\PhoneManageBundle\Controller
 */
class PhoneController extends BaseController
{
    /**
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function indexAction()
    {
        return $this->render('IcsocPhoneManageBundle:Phone:index.html.twig');
    }

    /**
     * 获取分机列表
     * @param Request $request
     * @return JsonResponse
     */
    public function listAction(Request $request)
    {
        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $sord = $request->get('sord', 'asc');
        $sidx = $request->get('sidx', 'id');
        $fliter = $request->get('fliter', '');
        $info = array(
            'pagination'=>array('rows'=>$rows, 'page'=>$page),
            'filter'=> !empty($fliter) ? json_decode($fliter, true) : array(),
            'sort'=>array('order'=>$sord,'field'=>$sidx),
        );
        $vcc_code = $this->getUser()->getVccCode();
        $list = $this->get('icsoc_data.model.phone')->getList(array('vcc_code'=>$vcc_code, 'info'=>json_encode($info)));
        $data = $res = array();
        if (isset($list['data']) && !empty($list['data'])) {
            $data['rows'] = $list['data'];
        }
        $data['page'] = isset($list['page']) ? $list['page'] : 1;
        $data['total'] = isset($list['totalPage']) ? $list['totalPage'] : 0;
        $data['records'] = isset($list['total']) ? $list['total'] : 0;

        return new JsonResponse($data);
    }

    /**
     * 添加分机
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function addAction(Request $request)
    {
        $queForm = $this->createForm('phone_info_form');
        if ($request->getMethod() == 'POST') {
            $arr = $request->get('phone_info_form');
            $arr['vcc_code'] = $this->getUser()->getVccCode();
            if ($arr['pho_type'] == 1 || $arr['pho_type'] == 2) {
                $arr['pho_num'] = explode("\r\n", $arr['pho_num']);
            }
            $msg = $this->get('icsoc_data.model.phone')->add($arr);
            if (isset($msg['code']) && ($msg['code'] == 200)) {
                $type = "success";
                $message = $this->get('translator')->trans('Add the extension of success');
            } else {
                $type = "danger";
                $message = $this->get('translator')->trans('Failed to add the extension').' '.isset($msg['message'])
                    ? $msg['message'] : '';
            }
            $data = array(
                'data'=>array(
                    'msg_detail' => $message,
                    'type' => $type,
                    'link' => array(
                        array('text'=>$this->get('translator')->trans('Continue to add'),
                            'href'=>$this->generateUrl('icsoc_phone_manage_add'), ),
                        array('text'=>$this->get('translator')->trans('The extension list'),
                            'href'=>$this->generateUrl('icsoc_phone_manage_index'), ),
                    ),
                ),
            );

            return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
        }

        return $this->render('IcsocPhoneManageBundle:Phone:phoneInfo.html.twig', array(
                'form' => $queForm->createView(),
            ));
    }

    /**
     * 删除分机
     * @param Request $request
     * @return JsonResponse
     */
    public function delAction(Request $request)
    {
        $ids = $request->get('id', 0);
        $arr['ids'] = explode(',', $ids);
        $arr['vcc_code'] = $this->getUser()->getVccCode();
        $phoNums = $this->container->get("doctrine.dbal.default_connection")->fetchAll(
            "SELECT id,pho_num FROM win_phone WHERE id IN ($ids) "
        );
        $pho = array();
        foreach ($phoNums as $nums) {
            $pho[$nums['id']] = $nums['pho_num'];
        }
        $msg = $this->get('icsoc_data.model.phone')->delete($arr);
        if (isset($msg['code']) && $msg['code'] == 500) {
            $success = $error = array();
            if (!empty($msg['data']['success'])) {
                foreach ($msg['data']['success'] as $suc) {
                    $success[] = isset($pho[$suc]) ? $pho[$suc] : '';
                }
            }
            if (!empty($msg['data']['fail'])) {
                foreach ($msg['data']['fail'] as $suc) {
                    $message = isset($pho[$suc]) ? $pho[$suc] : '';
                    $message.='有坐席在使用';
                    $error[] = $message;
                }
            }
            $message = $this->trans('Delete fail').'['.implode(',', $error)."] <br/>";
            $message.= $this->trans('Delete success').'['.implode(',', $success).'] <br/>';

            return new JsonResponse(array('message'=>$message, 'error'=>0));
        } else {
            return new JsonResponse(array('message'=>'删除失败['.$msg['message'].']'));
        }
    }
}
